package benchs

import (
	"database/sql"
	"fmt"
	"os"

	"gitee.com/chunanyong/zorm"
)

type Model struct {
	zorm.EntityStruct
	Id      int    `column:"id" qbs:"pk" orm:"auto" gorm:"primary_key" db:"id" xorm:"autoincr"`
	Name    string `column:"name" db:"name""`
	Title   string `column:"title" db:"title"`
	Fax     string `column:"fax" db:"fax"`
	Web     string `column:"web" db:"web"`
	Age     int    `column:"age" db:"age"`
	Right   bool   `column:"right" db:"right"`
	Counter int64  `column:"counter" db:"counter"`
}

func (*Model) TableName() string {
	return "models"
}

//GetTableName 获取表名称
func (entity *Model) GetTableName() string {
	return "models"
}

//GetPKColumnName 获取数据库表的主键字段名称.因为要兼容Map,只能是数据库的字段名称.
func (entity *Model) GetPKColumnName() string {
	return "id"
}

// NewModel initializes a new model struct for inserts
func NewModel() *Model {
	m := new(Model)
	m.Name = "Orm Benchmark"
	m.Title = "Just a Benchmark for fun"
	m.Fax = "99909990"
	m.Web = "http://baidu.com"
	m.Age = 100
	m.Right = true
	m.Counter = 2000

	return m
}

var (
	ORM_MULTI    int
	ORM_MAX_IDLE int
	ORM_MAX_CONN int
	ORM_SOURCE   string
)

// checkErr prints and exists on error
func checkErr(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(2)
	}
}

//wrapExecute sets timer for a benchmark step
func wrapExecute(b *B, cbk func()) {
	b.StopTimer()
	defer b.StartTimer()
	cbk()
}

// initDB recreates tables before executing any benchmark.
func initDB() {
	sqls := []string{
		`DROP TABLE IF EXISTS models;`,
		`CREATE TABLE models (
			id SERIAL NOT NULL,
			name text NOT NULL,
			title text NOT NULL,
			fax text NOT NULL,
			web text NOT NULL,
			age integer NOT NULL,
			"right" boolean NOT NULL,
			counter bigint NOT NULL,
			CONSTRAINT models_pkey PRIMARY KEY (id)
			) WITH (OIDS=FALSE);`,
	}

	DB, err := sql.Open("postgres", ORM_SOURCE)
	checkErr(err)
	defer DB.Close()

	err = DB.Ping()
	checkErr(err)

	for _, stmt := range sqls {
		_, err = DB.Exec(stmt)
		checkErr(err)
	}
}
